package com.share.trigger.http;

import com.alibaba.fastjson.JSON;
import com.share.domain.activity.model.entity.ActivityAccountEntity;
import com.share.domain.activity.model.entity.UserRaffleOrderEntity;
import com.share.domain.activity.service.IRaffleActivityAccountQuotaService;
import com.share.domain.activity.service.armory.IActivityArmory;
import com.share.domain.activity.service.quota.IRaffleActivityPartakeService;
import com.share.domain.award.model.entity.UserAwardRecordEntity;
import com.share.domain.award.model.valobj.AwardStateVo;
import com.share.domain.award.service.IAwardService;
import com.share.domain.rebate.model.entity.BehaviorEntity;
import com.share.domain.rebate.model.entity.BehaviorRebateOrderEntity;
import com.share.domain.rebate.model.valobj.BehaviorTypeVo;
import com.share.domain.rebate.service.IBehaviorRebateService;
import com.share.domain.strategy.model.entity.RaffleAwardEntity;
import com.share.domain.strategy.model.entity.RaffleFactorEntity;
import com.share.domain.strategy.model.entity.StrategyAwardEntity;
import com.share.domain.strategy.repository.IStrategyRepository;
import com.share.domain.strategy.service.IRaffleAward;
import com.share.domain.strategy.service.IRaffleStrategy;
import com.share.domain.strategy.service.armory.IStrategyArmory;
import com.share.trigger.api.IRaffleActivityService;
import com.share.trigger.api.dto.Activity.ActivityDrawRequestDTO;
import com.share.trigger.api.dto.Activity.ActivityDrawResponseDTO;
import com.share.trigger.api.dto.Activity.UserActivityAccountRequestDTO;
import com.share.trigger.api.dto.Activity.UserActivityAccountResponseDTO;
import com.share.trigger.api.dto.Raffle.RaffleAwardListRequestDTO;
import com.share.trigger.api.dto.Raffle.RaffleAwardListResponseDTO;
import com.share.types.enums.ResponseCode;
import com.share.types.exception.AppException;
import com.share.types.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/${app.config.api-version}/raffle/activity")
public class RaffleActivityController implements IRaffleActivityService {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    @Resource
    private IActivityArmory activityArmory;

    @Resource
    private IStrategyArmory strategyArmory;
    @Resource
    private IRaffleActivityPartakeService raffleActivityPartakeService;
    @Resource
    private IRaffleStrategy raffleStrategy;
    @Resource
    private IAwardService awardService;
    @Resource
    private IStrategyRepository strategyRepository;
    @Resource
    private IRaffleAward raffleAward;
    @Resource
    private IBehaviorRebateService behaviorRebateService;

    @Resource
    private IRaffleActivityAccountQuotaService quotaService;

    @Override
    @RequestMapping(value = "armory",method = RequestMethod.GET)
    public Response<Boolean> armory(@RequestParam Long activityId) {
        try {
            log.info("装配活动,数据预热,开始 activityId:{}",activityId);
            //装
            activityArmory.assembleActivitySkuByActivityId(activityId);
            strategyArmory.assembleLotteryStrategyByActivityId(activityId);
            Response<Boolean> response = Response.<Boolean>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .build();
            log.info("装配活动,数据预热,完成 activityId:{}",activityId);
            return response;
        }catch (Exception e){
            log.error("活动装配,数据预热,失败:activityId:{}",activityId);
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    @RequestMapping(value = "query_raffle_award_list",method = RequestMethod.POST)
    @Override
    public Response<List<RaffleAwardListResponseDTO>> queryRaffleAwardList(@RequestBody RaffleAwardListRequestDTO raffleAwardListRequestDTO) {
        try {
            log.info("策略:{}-查询奖品列表【开始】",raffleAwardListRequestDTO.getActivityId());
            //获得实体对象
            Long strategyId = strategyRepository.queryStrategyIdByActivityId(raffleAwardListRequestDTO.getActivityId());
            raffleAwardListRequestDTO.setStrategyId(strategyId);


            List<StrategyAwardEntity> strategyAwardEntities = raffleAward.queryRaffleStrategyAwardList(raffleAwardListRequestDTO.getStrategyId());
            //转换为DTO对象
            List<RaffleAwardListResponseDTO> raffleAwardListResponseDTOS = new ArrayList<>(strategyAwardEntities.size());
            for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
                raffleAwardListResponseDTOS.add(RaffleAwardListResponseDTO.builder()
                        .awardId(strategyAwardEntity.getAwardId())
                        .awardTitle(strategyAwardEntity.getAwardTitle())
                        .awardSubTitle(strategyAwardEntity.getAwardSubTitle())
                        .sort(strategyAwardEntity.getSort())
                        .build());
            }
            Response<List<RaffleAwardListResponseDTO>> res = Response.<List<RaffleAwardListResponseDTO>>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(raffleAwardListResponseDTOS)
                    .build();
            log.info("策略:{}-查询奖品列表【成功】",raffleAwardListRequestDTO.getStrategyId());
            return res;
        }catch (Exception e){
            log.error("策略:{}-查询奖品列表【失败】",raffleAwardListRequestDTO.getStrategyId());
            return Response.<List<RaffleAwardListResponseDTO>> builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }




    @Override
    @RequestMapping(value = "draw",method = RequestMethod.POST)
    public Response<ActivityDrawResponseDTO> draw(@RequestBody ActivityDrawRequestDTO activityDrawRequestDTO) {
        try {
            log.info("活动抽奖 userId:{}, activityId:{}",activityDrawRequestDTO.getUserId(),activityDrawRequestDTO.getActivityId());
            //参数校验
            String userId = activityDrawRequestDTO.getUserId();
            Long activityId = activityDrawRequestDTO.getActivityId();
            if(StringUtils.isBlank(userId)||activityId==null) {
             throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(),ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }

            //参与活动
            UserRaffleOrderEntity orderEntity = raffleActivityPartakeService.createOrder(activityDrawRequestDTO.getUserId(),activityDrawRequestDTO.getActivityId());
            log.info("活动抽奖,创建订单 userId:{}, activityId:{},orderId:{}",userId,activityId,orderEntity.getOrderId());

            //抽奖策略
            RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder()
                    .userId(userId)
                    .strategyId(orderEntity.getStrategyId())
                    .endDateTime(orderEntity.getEndDateTime())
                    .build());


            //存放结果
            UserAwardRecordEntity userAwardRecordEntity = UserAwardRecordEntity.builder()
                    .awardId(raffleAwardEntity.getAwardId())
                    .awardTitle(raffleAwardEntity.getAwardTitle())
                    .awardTime(new Date())
                    .awardState(AwardStateVo.create)
                    .userId(orderEntity.getUserId())
                    .activityId(orderEntity.getActivityId())
                    .strategyId(orderEntity.getStrategyId())
                    .orderId(orderEntity.getOrderId())
                    .awardConfig(raffleAwardEntity.getAwardConfig())
                    .build();
            awardService.saveUserAwardRecord(userAwardRecordEntity);

            Response<ActivityDrawResponseDTO> response = Response.<ActivityDrawResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(ActivityDrawResponseDTO.builder()
                            .awardId(raffleAwardEntity.getAwardId())
                            .awardTitle(raffleAwardEntity.getAwardTitle())
                            .awardIndex(raffleAwardEntity.getAwardId())
                            .build())
                    .build();
            log.info(JSON.toJSONString(response));
            return response;
        }catch (AppException e){
            log.error("活动抽奖失败:userId:{},activityId:{}",activityDrawRequestDTO.getUserId(),activityDrawRequestDTO.getActivityId());
            return Response.<ActivityDrawResponseDTO>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .build();
        }
    }

    @RequestMapping(value = "clendar_sign_rebate",method = RequestMethod.POST)
    @Override
    public Response<Boolean> calendarSignRebate(String userId) {
        try {
            log.info("【接口】【日历签到返利开始】：userId:{}",userId);
            BehaviorEntity behaviorEntity = new BehaviorEntity();
            behaviorEntity.setBehaviorTypeVo(BehaviorTypeVo.SIGN);
            behaviorEntity.setOutBusinessNo(dateFormat.format(new Date()));
            behaviorEntity.setUserId(userId);
            List<String> orderIds = behaviorRebateService.createOrder(behaviorEntity);
            log.info("【接口】【日历签到返利完成】：userId:{},orderIds:{}",userId,JSON.toJSONString(orderIds));
            return Response.<Boolean>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(true)
                    .build();
        }catch (AppException e){
            log.info("【异常】【接口】【日历签到返利】：userId:{}",userId,e);
            return Response.<Boolean>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .build();
        }catch (Exception e){
            log.info("【未知失败】【接口】【日历签到返利】：userId:{}",userId,e);
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data(false)
                    .build();

        }


    }

    /**
     * 签到奖励是否已获得
     * @param userId 用户id
     * @return
     */
    @Override
    @RequestMapping(value = "is_calender_sign_rebate",method = RequestMethod.POST)
    public Response<Boolean> isCalendarSignRebate(String userId) {
        try {
            log.info("[开始]查询是否已经领取过签到奖励:userId:{}",userId);
            String outBusinessNo = dateFormat.format(new Date());
            List<BehaviorRebateOrderEntity> behaviorRebateOrderEntities = behaviorRebateService.queryOrderByOutBusinessNo(userId, outBusinessNo);
            log.info("【结束】:是否已经领取过签到奖励userId:{},orderSize:{}",userId,behaviorRebateOrderEntities.size());
            return Response.<Boolean>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(!behaviorRebateOrderEntities.isEmpty())
                    .build();
        }catch (Exception e){
            log.info("[失败]查询是否已经领取过签到奖励:userId:{}",userId);
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data(false)
                    .build();
        }
    }

    @Override
    @RequestMapping(value = "query_user_activity_count",method = RequestMethod.POST)
    public Response<UserActivityAccountResponseDTO> queryUserActivityCount(UserActivityAccountRequestDTO request) {
        try {
            log.info("【开始】查询用户抽奖次数,userId:{},activityId:{}",request.getUserId(),request.getActivityId());
            //1.参数校验
            if(StringUtils.isBlank(request.getUserId())||null==request.getActivityId()){
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(),ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            ActivityAccountEntity activityAccountEntity = quotaService.queryActivityAccountEntity(request.getActivityId(), request.getUserId());
            UserActivityAccountResponseDTO responseDTO =new UserActivityAccountResponseDTO();
            responseDTO.setTotalCount(activityAccountEntity.getTotalCount());
            responseDTO.setTotalCountSurplus(activityAccountEntity.getTotalCountSurplus());
            responseDTO.setMonthCount(activityAccountEntity.getMonthCount());
            responseDTO.setMonthCountSurplus(activityAccountEntity.getMonthCountSurplus());
            responseDTO.setDayCount(activityAccountEntity.getDayCount());
            responseDTO.setDayCountSurplus(activityAccountEntity.getDayCountSurplus());
            log.info("【成功】查询用户抽奖次数,userId:{},activityId:{},结果：{}",request.getUserId(),request.getActivityId(),JSON.toJSONString(responseDTO));
            return Response.<UserActivityAccountResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(responseDTO)
                    .build();
        }catch (Exception e){
            log.info("【失败】查询用户抽奖次数,userId:{},activityId:{}",request.getUserId(),request.getActivityId());
            return Response.<UserActivityAccountResponseDTO>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }
}
